package cn.lkx.serviceorder.controller;


import cn.lkx.commonutils.JwtUtils;
import cn.lkx.commonutils.R;
import cn.lkx.serviceorder.entity.Order;
import cn.lkx.serviceorder.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author lkx
 * @since 2022-05-12
 */
@RestController
@RequestMapping("/serviceorder/order")
@CrossOrigin
public class OrderController {
    @Autowired
    private OrderService orderService;

    //1  生成订单
    @PostMapping("createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request){
        //根据存在请求头中的token得到会员id 然后根据课程id和会员id创建订单，返回订单号
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        String orderNo = orderService.saveOrder(courseId,memberId );
        return R.ok().data("orderNo",orderNo);
    }

    //2 根据订单号 order_no 查询订单信息
    @GetMapping("getOrderByNo/{orderNo}")
    public R getOrderByNo(@PathVariable String orderNo){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no",orderNo);
        Order order = orderService.getOne(queryWrapper);
        return R.ok().data("order",order);
    }

    //根据会员id和课程id查询订单信息 核对是否购买 给课程详情模块远程调用（完善课程详情免费的不需要购买）
    @GetMapping("isBuyCourse/{memberId}/{courseId}")
    public boolean isBuyCourse(@PathVariable String memberId,@PathVariable String courseId){
        //订单状态时 1 表示已购买
        int count = orderService.count(new QueryWrapper<Order>().eq("member_id", memberId)
                .eq("course_id", courseId).eq("status",1));
        return count>0;
    }
}

